﻿using System;
using System.Collections.Generic;
using System.Text;
using DevExpress.ExpressApp.DC;
using System.ComponentModel;
using DevExpress.Xpo;
using DevExpress.ExpressApp.Utils;
using DevExpress.Persistent.Base;
using System.IO;
using DevExpress.Persistent.Validation;

namespace DomainComponents.Common {
    [DomainComponent]
    [XafDefaultProperty("FileName")]
    public interface IPersistentFileData : IFileData, IEmptyCheckable {
        [System.ComponentModel.DefaultValue("")]
        new string FileName { get; set; }
        [System.ComponentModel.DefaultValue(0)]
        new int Size { get; set; }

        [ValueConverter(typeof(CompressionConverter)),
        MemberDesignTimeVisibility(false)]
        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
        byte[] Content { get; set; }

        #region IEmptyCheckable Members
        [NonPersistent, MemberDesignTimeVisibility(false)]
        new bool IsEmpty { get; }

        #endregion
    }

    [DomainLogic(typeof(IPersistentFileData))]
    public class PersistentFileDataLogic {
        public static void LoadFromStream(IPersistentFileData fileData, string fileName, Stream stream) {
            Guard.ArgumentNotNull(stream, "stream");
            Guard.ArgumentNotNullOrEmpty(fileName, "fileName");

            fileData.FileName = fileName;
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            fileData.Content = bytes;
        }

        public static void SaveToStream(IPersistentFileData fileData, Stream stream) {
            if(string.IsNullOrEmpty(fileData.FileName)) {
                throw new InvalidOperationException();
            }
            stream.Write(fileData.Content, 0, fileData.Size);
            stream.Flush();
        }

        public static void Clear(IPersistentFileData fileData) {
            fileData.Content = null;
            fileData.FileName = String.Empty;
        }

        public static void AfterChange_Content(IPersistentFileData fileData) {
            if(fileData != null && fileData.Content != null) {
                fileData.Size = fileData.Content.Length;
            }
            else {
                fileData.Size = 0;
            }
        }

        public static bool Get_IsEmpty(IPersistentFileData fileData) {
            return string.IsNullOrEmpty(fileData.FileName);
        }
    }
}
